<?php include 'assets/tool/01_function.php'; ?>

<?php
class ImagesController extends AdminController
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    //public $layout='//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
                'accessControl', // perform access control for CRUD operations
                'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array("allow", // allow authenticated user to perform 'create' and 'update' actions
                    "actions"    => array("index","list","listdetail","edit","delete","save","UploadImage","DeleteFile"),
                    "users" => array("@"),
                    "expression" => "Yii::app()->user->authority == Account::ADMIN"
            ),
            array("deny",  // deny all users
                    "users" => array("*")
            )
        );
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $i_amountPerPage = 100;
        $i_page          = 1;
        $s_columnName    = "insert";
        $s_sortMethod    = "DESC";
        $arr_model       = null;
        $arr_errorCode   = null;
        $s_errorMessage  = null;
        
        //prepare where statement
        $s_where = "`is_system` = 1";
        
        $s_order = "`".$s_columnName."` ".$s_sortMethod;

        $arr_model = Library::getDataByParameter($i_page, $i_amountPerPage, $s_order, $s_where, $i_total);
        if( ErrorEntity::isErrorEntity($arr_model) )
        {
            array_push($arr_errorCode, $arr_model->errCode);
        }

        //Set error message
        if( $arr_errorCode!= null )
        {
            $s_errorMessage = $this->getErrorMessage($arr_errorCode);
        }

        $this->render(
            "index",
            array(
                "arr_library" => $arr_model,
                "s_errMsg"    => $s_errorMessage
            )
        );
    }

    public function actionList()
    {
        $i_amountPerPage    = isset($_REQUEST["amountPerPage"]) ? $_REQUEST["amountPerPage"]    : 0;
        $i_page             = isset($_REQUEST["page"])            ? $_REQUEST["page"]           : 0;
        $s_filter           = isset($_REQUEST["txt_filter"])    ? $_REQUEST["txt_filter"]       : null;
        $s_types            = isset($_REQUEST["sl_type"])        ? $_REQUEST["sl_type"]         : null;
        $s_columnName       = isset($_REQUEST["columnName"])    ? $_REQUEST["columnName"]       : "insert";
        $s_sortMethod       = isset($_REQUEST["sortMethod"])    ? $_REQUEST["sortMethod"]       : "DESC";
        $i_total            = 0;
        $arr_model          = null;
        $arr_errorCode      = null;

        //prepare where statement
        $s_where = "
                `library` LIKE '%".$s_types."%' AND
                `name`    LIKE '%".$s_filter."%'
                        ";

        $s_order = "`".$s_columnName."` ".$s_sortMethod;

        if( $arr_errorCode == null && $i_page != 0 ) {
            $arr_model = Items::getDataByParameter($i_page, $i_amountPerPage, $s_order, $s_where, $i_total);
        }
        else
            array_push($arr_errorCode, "ERR_1");

        if( $arr_errorCode == null && is_array($arr_model) )
        {
            $this->renderPartial(
                    "list",
                    array(
                            "arr_data"        => $arr_model,
                            "i_totalItem"     => $i_total,
                            "i_amountPerPage" => $i_amountPerPage,
                            "i_currentPage"   => $i_page
                    )
            );
        }//End if
        else
            array_push($arr_errorCode, "ERR_2");

        if( $arr_errorCode!= null )
        {
            $s_errorMessage = $this->getErrorMessage($arr_errorCode);
            $this->renderPartial("list", array( "error" => $s_errorMessage));
        }
    }

    public function actionEdit()
    {
        $i_amountPerPage = 100;
        $i_page          = 1;
        $s_columnName    = "insert";
        $s_sortMethod    = "ASC";
        $arr_model       = null;
        $arr_errorCode   = null;
        $s_errorMessage  = null;

        //prepare where statement
        $s_where = "`is_system` = 1";
        
        $s_order = "`".$s_columnName."` ".$s_sortMethod;

        $arr_model = Library::getDataByParameter($i_page, $i_amountPerPage, $s_order, $s_where, $i_total);
        if( ErrorEntity::isErrorEntity($arr_model) )
        {
            array_push($arr_errorCode, $arr_model->errCode);
        }

        //Set error message
        if( $arr_errorCode!= null )
        {
            $s_errorMessage = $this->getErrorMessage($arr_errorCode);
        }

        $this->render(
            "edit",
            array(
                "arr_library" => $arr_model,
                "s_errMsg"    => $s_errorMessage
            )
        );
    }

    /** actionSave ==================================
     * @author   TuanNguyen
     * @desc:    When user click button btn_saveImage
     *           save array of images to database
     * @return:  JSON array
     * ============================================== */
    public function actionSave()
    {
        //Initial Parameter
        $arr_errors = array();
        
        //Check Request Parameter
        $b_result = self::checkSaveParamRequest($arr_errors);
        if( !$b_result )
        {
            $s_errorMessage = self::getErrorMessage($arr_errors);
            exit(json_encode(array( "error" => $s_errorMessage)));
        }
        
        //Save to database
        $i_library         = $_REQUEST["sl_type"];
        $arr_imgUrl        = $_REQUEST["arr_imgUrl"];
        $arr_imgName       = $_REQUEST["arr_imgName"];
        $s_insertStatement = "";
        $date_insert       = new DateTime();
        
        //add value to staement to prepare multi insert to database
        for ($i=0; $i<count($arr_imgUrl); $i++)
        {
            $s_insertStatement .= "(".$i_library.",'".$arr_imgName[$i]."', '".$arr_imgUrl[$i]."', '".$arr_imgName[$i]."', '".TypeConfEnum::IMAGE."', '".$date_insert->format("Y-m-d H:i:s")."'),";
        }
        
        //Remove last comma in statement
        $s_insertStatement = substr($s_insertStatement, 0, -1);
        //add data to db
        $b_result = Items::addItemsToDb($s_insertStatement);
        if( ErrorEntity::isErrorEntity($b_result) )
        {
            $s_errorMessage = self::getErrorMessage($b_result);
            exit(json_encode(array( "error" => $s_errorMessage)));
        }
        
        if( $b_result )
        {
            //print JSON Encode to view
            exit(json_encode(array( "result" => "Thành Công")));
        }
        else
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_1";
            $o_error->param     = null;
            array_push($arr_errors, $o_error);
            
            $s_errorMessage = $this->getErrorMessage($arr_errors);
            exit(json_encode(array( "error" => $s_errorMessage)));
        }//End Else

        Yii::app()->end();
    }

    /** actionSave ==================================
     * @author   TuanNguyen
     * @desc:    When user click button btn_saveImage
     *           save array of images to database
     * @return:  boolean
     * ============================================== */
    public function actionDeleteFile()
    {
        if( isset($_REQUEST["s_imgName"])  == false ||
            isset($_REQUEST["sl_type"])    == false )
        {
            $o_error             = new ErrorEntity();
            $o_error->errCode    = "ERR_3";
            $o_error->param      = null;
            $s_errorMessage      = self::getErrorMessage($o_error);
            exit($s_errorMessage);
        }

        if( $_REQUEST["s_imgName"] == "" )
        {
            $o_error             = new ErrorEntity();
            $o_error->errCode    = "ERR_5";
            $o_error->param      = array("fieldName"=>"image name");
            $s_errorMessage      = self::getErrorMessage($o_error);
            exit($s_errorMessage);
        }

        if( $_REQUEST["sl_type"] == "" )
        {
            $o_error             = new ErrorEntity();
            $o_error->errCode    = "ERR_5";
            $o_error->param      = array("fieldName"=>"image category");
            $s_errorMessage      = self::getErrorMessage($o_error);
            exit($s_errorMessage);
        }

        if( !is_numeric($_REQUEST["sl_type"]) )
        {
            $o_error          = new ErrorEntity();
            $o_error->errCode = "ERR_4";
            $o_error->param   = array("fieldName"=>"library", "formatName"=>"numeric");
            $s_errorMessage   = self::getErrorMessage($o_error);
            exit($s_errorMessage);
        }

        //Init request parameter
        $i_library     = $_REQUEST["sl_type"];
        $s_imgFileName = $_REQUEST["s_imgName"];
        $o_library     = Library::getDataByID($i_library);

        $s_imgFolder = realpath("images/".$o_library->folder);
        $b_isHasFile = is_readable($s_imgFolder."\\".$s_imgFileName);
        
        if($b_isHasFile)
        {
            unlink($s_imgFolder."\\".$s_imgFileName);
            echo true;
        }
        else 
            echo false;

        Yii::app()->end();
        return true;
    }


    /**
     * Upload Multi-Image.
     *
     * @param integer $id the ID of the model to be deleted
     */
    public function actionUploadImage()
    {
        if( isset($_REQUEST["sl_type"])== false    ||
            isset($_REQUEST["token"])== false      ||
            isset($_REQUEST["timestamp"])== false )
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_3";
            $o_error->param     = null;
            $s_errorMessage     = self::getErrorMessage($o_error);
            $arr_temp           = array("error" => $s_errorMessage);
            exit(json_encode($arr_temp));
        }

        if( $_REQUEST["sl_type"] == "" )
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_5";
            $o_error->param     = array("fieldName"=>"image category");
            $s_errorMessage     = self::getErrorMessage($o_error);
            $arr_temp           = array("error" => $s_errorMessage);
            exit(json_encode($arr_temp));
        }

        if( !is_numeric($_REQUEST["sl_type"]) )
        {
            $o_error          = new ErrorEntity();
            $o_error->errCode = "ERR_4";
            $o_error->param   = array("fieldName"=>"library", "formatName"=>"numeric");
            $s_errorMessage   = self::getErrorMessage($o_error);
            $arr_temp         = array("error" => $s_errorMessage);
            exit(json_encode($arr_temp));
        }

        //Init request parameter
        $i_library     = $_REQUEST["sl_type"];
        $s_verifyToken = md5("unique_salt".$_REQUEST["timestamp"]);
        $s_token       = $_REQUEST["token"];
        $o_library     = Library::getDataByID($i_library);

        $s_folderPath    = "images/".$o_library->folder;
        $i_imgWidth      = $o_library->width;
        $i_imgHeight     = $o_library->height;

        if ( !empty($_FILES) && 
             ($s_token == $s_verifyToken) )
        {
            // Validate the file type
            $arr_types = array('jpg','jpeg','gif','png');

            $arr_result = uploadImageAjax($arr_types, "Filedata", $s_folderPath, $i_imgWidth, $i_imgHeight);
            if( is_array($arr_result) == true )
                exit(json_encode($arr_result));
            else
            {
                $arr_result = array("result" => $arr_result);
                exit(json_encode($arr_result));
            }

        }//End if

        Yii::app()->end();
    }

    /** checkSaveParamRequest =========================
     * @author   TuanNguyen
     * @desc     Check request param when user press btn_saveImage
     *           set reference parameter if there are an error
     * @param    array &$arr_errors: array to content error entity
     * @return   boolean: true(No error), false(error)
     * ============================================== */
    private function checkSaveParamRequest(array &$arr_errors)
    {
        if( isset($_REQUEST["sl_type"])== false ||
            isset($_REQUEST["arr_imgUrl"])== false ||
            isset($_REQUEST["arr_imgName"])== false )
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_3";
            $o_error->param     = null;
            array_push($arr_errors, $o_error);
            return false;
        }

        if( !is_array($_REQUEST["arr_imgUrl"]) )
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_4";
            $o_error->param     = array("fieldName"=>"image urls", "formatName"=>"array");
            array_push($arr_errors, $o_error);
            return false;
        }

        if( !is_array($_REQUEST["arr_imgName"]) )
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_4";
            $o_error->param     = array("fieldName"=>"image names", "formatName"=>"array");
            array_push($arr_errors, $o_error);
            return false;
        }

        if( count($_REQUEST["arr_imgUrl"]) < 1 )
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_5";
            $o_error->param     = array("fieldName"=>"Image Url List");
            array_push($arr_errors, $o_error);
            return false;
        }

        if( count($_REQUEST["arr_imgName"]) < 1 )
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_5";
            $o_error->param     = array("fieldName"=>"image names");
            array_push($arr_errors, $o_error);
            return false;
        }

        return true;
    }

    /** getErrorMessage =============================
     * @author   TuanNguyen
     * @desc     get error message from array of error entity
     *           set reference parameter if there are an error
     * @param    $errorEnts: array of error entity or error entity
     * @return   string: error message
     * ============================================== */
    private function getErrorMessage($errorEnts)
    {
        $arr_errorMessage    = array(
                "ERR_1" => "There are an error with parameters in SQL statement. ",
                "ERR_2" => "SQLException",
                "ERR_3" => "Recieved Parameter is wrong or missing. ",
                "ERR_4" => "format of fieldName is formatName, please type value as formatName format . ",
                "ERR_5" => "fieldName is empty, please set value for it. ",
                "ERR_6" => "ImageType don't exist in image configuration. "
        );
        
        //Return error message
        if ( is_array($errorEnts) )
        {
            return ErrorEntity::setErrorMessageByArray($errorEnts, $arr_errorMessage);
        }
        elseif ( $errorEnts instanceof ErrorEntity )
        {
            return ErrorEntity::setErrorMessageByEntity($errorEnts, $arr_errorMessage);
        }
    }
}